package com.hello.web.service;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.hello.common.enums.ResponseCodeEnum;
import com.hello.common.exception.BizException;
import com.hello.common.utils.Response;
import com.hello.web.config.SharedData;
import com.hello.web.domain.bo.UpdatePasswordBO;
import com.hello.web.domain.bo.UserLoginBO;
import com.hello.web.domain.entity.UserDO;
import com.hello.web.domain.mapper.UserMapper;
import com.hello.web.domain.vo.FindUserInfoVO;
import com.hello.web.utils.RedisUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class LoginService {

    private final UserMapper userMapper;

    private final RedisUtils redisUtils;

    private final SharedData sharedData;

/*    //登录
    public SaTokenInfo login(UserLoginBO bo) {
        SaTokenInfo responseInfo = new SaTokenInfo();
        UserDO userDO = userMapper.findByUsername(bo.getUsername());
        if (userDO == null) {
            throw new BizException(ResponseCodeEnum.USERNAME_OR_PWD_ERROR);
        }
        if (!userDO.getPassword().equals(SecureUtil.md5(bo.getPassword()))) {
            throw new BizException(ResponseCodeEnum.USERNAME_OR_PWD_ERROR);
        }
        StpUtil.login(userDO.getId());

        SaTokenInfo saToken = StpUtil.getTokenInfo();

        redisUtils.set("token",saToken.tokenValue);

        return saToken;
    }*/


    /**
     * 修改密码
     */
    public Response updatePassword(UpdatePasswordBO bo) {
        // 拿到用户名、密码
        String username = bo.getUsername();
        String password = bo.getPassword();

        // 加密密码
        String encodePassword = SecureUtil.md5(password);
        // 更新到数据库
        int count = userMapper.updatePasswordByUsername(username, encodePassword);
        return count == 1 ? Response.success() : Response.fail(ResponseCodeEnum.USERNAME_NOT_FOUND);
    }

    /**
     * 获取当前登录用户信息
     * @return
     */
    public Response findUserInfo() {
        // 获取存储在 ThreadLocal 中的用户信息
        long loginId = StpUtil.getLoginIdAsLong();
        UserDO userDO = userMapper.selectById(loginId);
        return Response.success(userDO);
    }

    public Response redisToken() {

        String tokenValue = redisUtils.get("token", String.class);

        if (StrUtil.isBlank(tokenValue)){
            throw new BizException(ResponseCodeEnum.LOGIN_EXPIRED);
        }

        if (StpUtil.isLogin()) {
            throw new BizException(ResponseCodeEnum.LOGIN_EXPIRED);
        }

        return Response.success(tokenValue);
    }

    public Response login(UserLoginBO bo) {

        sharedData.setValue(bo.getUserId());

        return Response.success();
    }

    public Response userInfo() {

        return Response.success(sharedData.getValue());
    }
}
